package com.ugoodtech.mdcc.client.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.LevelStrUtil;
import com.ugoodtech.mdcc.client.Utils.CheckUtil;
import com.ugoodtech.mdcc.client.dto.ComplaintReportAnswer;
import com.ugoodtech.mdcc.client.dto.ComplaintReportAudit;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.AliSmsProvider;
import com.ugoodtech.mdcc.client.service.ComplaintReportAuditService;
import com.ugoodtech.mdcc.client.service.ComplaintReportService;
import com.ugoodtech.mdcc.client.service.ComplaintUserService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.AdminUserVo;
import com.ugoodtech.mdcc.core.dto.ComplaintSearch;
import com.ugoodtech.mdcc.core.dto.ComplaintTimeResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.ComplaintSearchService;
import com.ugoodtech.mdcc.core.service.ComplaintTimeService;
import com.ugoodtech.mdcc.core.service.UserAdminService;
import com.ugoodtech.mdcc.core.service.WechatService;
import com.ugoodtech.mdcc.core.utils.ComplaintReportUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class}, propagation = Propagation.REQUIRED)
public class ComplaintReportAuditServiceImpl implements ComplaintReportAuditService {

    private static Logger logger = LoggerFactory.getLogger(ComplaintReportAuditServiceImpl.class);

    @Autowired
    private ComplaintReportRepository complaintReportRepository;

    @Autowired
    private ComplaintReportLogRepository complaintReportLogRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private ComplaintReportDataRepository complaintReportDataRepository;

    @Autowired
    private AliSmsProvider aliSmsProvider;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private ComplaintSearchService complaintSearchService;

    @Autowired
    private ComplaintUserService complaintUserService;

    @Autowired
    private ComplaintReportService complaintReportService;

    @Autowired
    private ComplaintUserRepository complaintUserRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private ComplaintTimeService complaintTimeService;

    @Autowired
    private UserAdminService userAdminService;

    @Autowired
    private ComplaintSolutionDataRepository complaintSolutionDataRepository;

    /**
     * 获取投诉报告审核
     *
     * @param pageable
     * @return
     */
    @Override
    public JsonResponse getAuditComplaintReport(Pageable pageable, Integer reportStatus, ComplaintSearch complaintSearch,User user) {
        logger.info("获取审核菜单中的报告");

        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        booleanBuilder.and(qComplaintReport.deleted.eq(false));
        booleanBuilder.and(qComplaintReport.enabled.eq(true));
        booleanBuilder.and(qComplaintReport.auditFalse.eq(false));
        if (reportStatus.equals(0)) {
            //未审核:0
            booleanBuilder.and(qComplaintReport.reportStatus.eq(Constants.BEGIN));
            booleanBuilder.and(qComplaintReport.audit.eq(false));
        } else if (reportStatus.equals(1)) {
            //已审核:1
            booleanBuilder.and(qComplaintReport.audit.eq(true));
            booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.TIME_OUT));
            booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.STOP));
            booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.OTHER_FOLLOW));
        } else if (reportStatus.equals(2)) {
            //返回投诉:2
            BooleanBuilder orBuilder = new BooleanBuilder();
            orBuilder.or(qComplaintReport.reportStatus.eq(Constants.TIME_OUT));
            orBuilder.or(qComplaintReport.reportStatus.eq(Constants.STOP));
            orBuilder.or(qComplaintReport.reportStatus.eq(Constants.OTHER_FOLLOW));
            orBuilder.or(qComplaintReport.reportStatus.eq(Constants.BEGIN));
            booleanBuilder.and(qComplaintReport.back.eq(true));
            booleanBuilder.and(orBuilder);
        }
        if (CheckUtil.objCheckIsNull(complaintSearch)) {
            List<Long> complaintIds = complaintSearchService.searchComplaintReport(complaintSearch, user);
            if (!complaintIds.isEmpty()) {
                booleanBuilder.and(qComplaintReport.id.in(complaintIds));
            }else{
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ComplaintReport> complaintReportList = complaintReportRepository.findAll(booleanBuilder, pageable);
        List<ComplaintReportAudit> auditList = getResponse(complaintReportList.getContent());
        Page<ComplaintReportAudit> page = new PageImpl(auditList, pageable, complaintReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 获取投诉报告跟进
     *
     * @param pageable
     * @param reportStatus
     * @param user
     * @return
     */
    @Override
    public JsonResponse getFollowComplaintReport(Pageable pageable, Integer reportStatus, User user, ComplaintSearch complaintSearch) {
        logger.info("获取跟进菜单中的投诉报告");
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        booleanBuilder.and(qComplaintReport.deleted.eq(false));
        booleanBuilder.and(qComplaintReport.enabled.eq(true));
        booleanBuilder.and(qComplaintReport.audit.eq(true));
        booleanBuilder.and(qComplaintReport.back.eq(false));
        booleanBuilder.and(qComplaintReport.auditFalse.eq(false));

        if (reportStatus.equals(0)) {
            logger.info("获取待领取的投诉单");
            BooleanBuilder orBuilder = new BooleanBuilder();
            orBuilder.or(qComplaintReport.needUserList.any().eq(user.getId()));
            orBuilder.or(qComplaintReport.leader.eq(user.getId()));
            booleanBuilder.and(orBuilder);

            orBuilder = new BooleanBuilder();
            orBuilder.or(qComplaintReport.reportStatus.eq(Constants.BEGIN));
            booleanBuilder.and(orBuilder);
            booleanBuilder.and(qComplaintReport.receive.eq(false));
        } else if (reportStatus.equals(1)) {
            logger.info("获取处理中的投诉单");
            booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.COMPLETE));
            booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.STOP));
            booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.TIME_OUT));
            booleanBuilder.and(qComplaintReport.receive.eq(true));
            booleanBuilder.and(qComplaintReport.followUser.id.eq(user.getId()));
        } else if (reportStatus.equals(2)) {
            logger.info("获取已处理的投诉单");
            BooleanBuilder orBuilder = new BooleanBuilder();
            orBuilder.or(qComplaintReport.reportStatus.eq(Constants.COMPLETE));
            booleanBuilder.and(orBuilder);
            booleanBuilder.and(qComplaintReport.followUser.id.eq(user.getId()));
        }
        if (CheckUtil.objCheckIsNull(complaintSearch)) {
            List<Long> complaintIds = complaintSearchService.searchComplaintReport(complaintSearch, user);
            if (!complaintIds.isEmpty()) {
                booleanBuilder.and(qComplaintReport.id.in(complaintIds));
            }else {
                return JsonResponse.successResponseWithPageData(new PageImpl(new ArrayList(), pageable, 0));
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<ComplaintReport> complaintReportList = complaintReportRepository.findAll(booleanBuilder, pageable);
        List<ComplaintReportAudit> auditList = getResponse(complaintReportList.getContent());
        Page<ComplaintReportAudit> page = new PageImpl(auditList, pageable, complaintReportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    /**
     * 审核不通过投诉报告
     *
     * @param user
     * @param auditNode
     * @param complaintReportId
     * @return
     */
    @Override
    public JsonResponse auditComplaintReportFalse(User user, String auditNode, Long complaintReportId) {
        logger.info("审核不通过投诉报告");
        ComplaintReport complaintReport = complaintReportRepository.findOne(complaintReportId);
        if (null == complaintReport) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该投诉");
        }
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (null == userProfile || StringUtils.isEmpty(userProfile.getRealName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        //查询报告创建者
        UserProfile createProfile = userProfileRepository.findByUserId(complaintReport.getUser().getId());
        if (null == createProfile || StringUtils.isEmpty(createProfile.getRealName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        //更新报告
        complaintReport.setAuditFalse(true);
        complaintReport.setAuditFalseNote(auditNode);
        complaintReportRepository.save(complaintReport);

        //记录日志
        ComplaintReportLog complaintReportLog = new ComplaintReportLog();
        complaintReportLog.setUserName(userProfile.getRealName());
        complaintReportLog.setUser(user);
        complaintReportLog.setReportStatus("审核不通过：" + auditNode);
        complaintReportLog.setTime(new SimpleDateFormat(Constants.DATE_TIME_FORMAT).format(new Date()));
        complaintReportLog.setComplaintReportId(complaintReport.getId());
        complaintReportLogRepository.save(complaintReportLog);
        //审核不通过通知
        sendAuditFalil(complaintReport);
        return JsonResponse.successResponse();
    }


    private void sendAuditFalil(ComplaintReport complaintReport) {
        //获取管理员手机号
        //获取管理员手机号
        AdminUserVo adminUserVo = userAdminService.getAdminUser();
        List<User> oppenIdUser = adminUserVo.getUserList();
        oppenIdUser.add(complaintReport.getUser());
        if (null != complaintReport.getLeader() && complaintReport.getLeader() != 0) {
            User user = userRepository.findOne(complaintReport.getLeader());
            if (null != user && StringUtils.isNotEmpty(user.getUsername())) {
                oppenIdUser.add(user);
            }
        } else if (!complaintReport.getNeedUserList().isEmpty()) {
            for (Long userId : complaintReport.getNeedUserList()) {
                User user = userRepository.findOne(userId);
                if (null != user && StringUtils.isNotEmpty(user.getUsername())) {
                    oppenIdUser.add(user);
                }
            }
        }
        ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 194L);
        StringBuffer brandBuffer = new StringBuffer("");
        if (null != complaintReport && StringUtils.isNotEmpty(complaintReportData.getAnswerId())) {
            for (String brandIdStr : complaintReportData.getAnswerId().split(",")) {
                if (!brandIdStr.equals("447")) {
                    QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(brandIdStr));
                    if (null != questionAnswerOption && StringUtils.isNotEmpty(questionAnswerOption.getName())) {
                        brandBuffer.append(questionAnswerOption.getName() + ",");
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(complaintReportData.getAnswerOther())) {
            brandBuffer.append(complaintReportData.getAnswerOther());
        }
        String customer = complaintReportService.getComplaintReportCustomer(complaintReport.getId());
        try {
            String remark = "您的投诉审核不通过，请按要求修改，重新提交。";
            String firstStr = "投诉审核通知";
            aliSmsProvider.auditFalseComplaint(complaintReport.getUser().getUsername(), customer);
            for (User openUser : oppenIdUser) {
                wechatService.pushWechatMessage(openUser, "i0Bxtwki-LD4ytCJ-8VDO8g3ThpSHC5h3ysfSi7oh3s", Constants.WECHAT_PUSH_URL, firstStr,
                        remark, customer, brandBuffer.toString(), complaintReport.getCreationTimeStr(), "", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 审核指派投诉报告
     *
     * @param user
     * @param validTime
     * @param complaintReportId
     * @param leaderUser
     * @param needFollowUserId
     * @return
     */
    @Override
    public JsonResponse auditComplaintReport(User user, Long validTime, Long complaintReportId, Long leaderUser,
                                             String needFollowUserId, ComplaintReportAnswer complaintReportDataList, String otherFollowNode) {
        logger.info("审核指派投诉报告");
        ComplaintReport complaintReport = complaintReportRepository.findOne(complaintReportId);
        if (null == complaintReport) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该投诉");
        }
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (null == userProfile || StringUtils.isEmpty(userProfile.getRealName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        //查询报告创建者
        UserProfile createProfile = userProfileRepository.findByUserId(complaintReport.getUser().getId());
        if (null == createProfile || StringUtils.isEmpty(createProfile.getRealName())) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        //更新投诉单报告
        updateComplaintReport(complaintReport, complaintReportDataList);
        //设置投诉报告日志
        Date nowDate = new Date();
        ComplaintReportLog complaintReportLog = new ComplaintReportLog();
        complaintReportLog.setTime(new SimpleDateFormat(Constants.DATE_TIME_FORMAT).format(nowDate));
        complaintReportLog.setUserName(userProfile.getRealName());
        complaintReportLog.setUser(user);

        complaintReportLog.setComplaintReportId(complaintReportId);


        //修改投诉报告状态
        if (null == complaintReport.getFirstAuditTime()) {
            complaintReport.setFirstAuditTime(nowDate);
        }
        //插入一个空的记录
        complaintUserService.addComplaintUser(complaintReport);

        complaintReport.setAudit(true);
        complaintReport.setReceive(false);
        complaintReport.setBack(false);
        complaintReport.setSendMessage(false);
        complaintReport.setReportStatus(Constants.BEGIN);
        complaintReport.setAuditTime(nowDate);
        complaintReport.setUpdateTime(nowDate);
        complaintReport.setValidTime(validTime);
        complaintReport.setFollowUser(null);
        complaintReport.setAuditFalse(false);
        if (StringUtils.isNotEmpty(otherFollowNode)) {
            complaintReport.setOtherFollowNote(otherFollowNode);
            complaintReportLog.setNote(otherFollowNode);
        } else {
            complaintReport.setOtherFollowNote("");
        }

        //获取被指派人的信息
        StringBuffer stringBuffer = new StringBuffer("");
        if (StringUtils.isNotEmpty(needFollowUserId)) {
            logger.info("指派的是技术人员或者销售");
            List<Long> needFollowUserList = new ArrayList<>();
            for (String userId : needFollowUserId.split(",")) {
                userProfile = userProfileRepository.findByUserId(Long.valueOf(userId));
                if (null == userProfile || StringUtils.isEmpty(userProfile.getRealName())) {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到指派对象");
                }
                needFollowUserList.add(Long.valueOf(userId));
                stringBuffer.append(userProfile.getRealName() + "、");
            }
            //设置投诉报告日志--转派给的人
            complaintReportLog.setNeedFollowUser(stringBuffer.substring(0, stringBuffer.length() - 1));
            complaintReportLog.setReportStatus("审核指派：技术人员");
            //设置投诉报告--转派给的人
            complaintReport.setLeaderFollow(false);
            complaintReport.setNeedUserList(needFollowUserList);
            complaintReport.setLeader(null);
        } else if (null != leaderUser && leaderUser != 0) {
            logger.info("指派的是上级领导");
            //设置投诉报告--转派给的人
            complaintReport.setLeader(leaderUser);
            userProfile = userProfileRepository.findByUserId(leaderUser);
            if (null == userProfile || StringUtils.isEmpty(userProfile.getRealName())) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到此上级领导");
            }
            complaintReport.setLeaderFollow(true);
            complaintReport.setNeedUserList(null);
            //设置投诉报告日志--转派给的人
            complaintReportLog.setNeedFollowUser(userProfile.getRealName());
            complaintReportLog.setReportStatus("审核指派：上级领导");
        } else {
            logger.info("未传入指派人");
            return JsonResponse.errorResponseWithError("抱歉", "请指派跟进人员");
        }
        complaintReportLogRepository.save(complaintReportLog);
        complaintReportRepository.save(complaintReport);
        sendMessage(complaintReport, createProfile.getRealName());
        return JsonResponse.successResponse();
    }

    /**
     * 发送审核指派短信
     *
     * @param complaintReport
     * @param createUser
     */
    private void sendMessage(ComplaintReport complaintReport, String createUser) {
        //获取管理员手机号
        AdminUserVo adminUserVo = userAdminService.getAdminUser();
        StringBuilder telephoneStr = adminUserVo.getTelephoneStr();
        List<User> oppenIdUser = adminUserVo.getUserList();

        String customer = complaintReportService.getComplaintReportCustomer(complaintReport.getId());
        ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 188L);
        String level = "高级";
        if (null != complaintReportData && StringUtils.isNotEmpty(complaintReportData.getAnswerId())) {
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(complaintReportData.getAnswerId()));
            if (null != answerOption && StringUtils.isNotEmpty(answerOption.getName())) {
                level = LevelStrUtil.getLevelStr(answerOption.getName());
            }
        }
        String follow = "技术人员";
        if (null != complaintReport.getLeader() && complaintReport.getLeader() != 0) {
            UserProfile userProfile = userProfileRepository.findByUserId(complaintReport.getLeader());
            if (null != userProfile && StringUtils.isNotEmpty(userProfile.getRealName())) {
                follow = userProfile.getRealName();
                telephoneStr.append(userProfile.getUser().getUsername());
                oppenIdUser.add(userProfile.getUser());
            }
        } else if (!complaintReport.getNeedUserList().isEmpty()) {
            StringBuffer stringBuffer = new StringBuffer("");
            for (Long userId : complaintReport.getNeedUserList()) {
                UserProfile userProfile = userProfileRepository.findByUserId(userId);
                if (null != userProfile && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    stringBuffer.append(userProfile.getRealName() + ",");
                    telephoneStr.append(userProfile.getUser().getUsername() + ",");
                }
            }
            follow = stringBuffer.substring(0, stringBuffer.length() - 1);
        }
        //查询问题类型
        StringBuffer problemBuffer = new StringBuffer("");
        complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 195L);
        if (null != complaintReportData && StringUtils.isNotEmpty(complaintReportData.getAnswerId())) {
            for (String answerId : complaintReportData.getAnswerId().split(",")) {
                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(answerId));
                if (null != answerOption && StringUtils.isNotEmpty(answerOption.getName())) {
                    problemBuffer.append(answerOption.getName() + ",");
                }
            }
        }
        String solutionTypeAnswerId = "";
        if (null != complaintReport.getSolutionId()) {
            ComplaintSolutionData complaintSolutionData = complaintSolutionDataRepository.selectSolutionDate(complaintReport.getSolutionId(), 206L);
            if (null != complaintSolutionData && StringUtils.isNotEmpty(complaintSolutionData.getAnswerId())) {
                solutionTypeAnswerId = complaintSolutionData.getAnswerId();
            }
        }
        String serverName = "";
        if (null != complaintReport.getUser()) {
            QComplaintReportLog qComplaintReportLog = QComplaintReportLog.complaintReportLog;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qComplaintReportLog.complaintReportId.eq(complaintReport.getId()));
            List<ComplaintReportLog> all = (List<ComplaintReportLog>) complaintReportLogRepository
                .findAll(booleanBuilder);
            serverName = all.get(all.size() - 1).getUserName();
        }
        try {
            SendSmsResponse sendSmsResponse;
            if (StringUtils.isNotEmpty(solutionTypeAnswerId) && solutionTypeAnswerId.equals("444")) {
                sendSmsResponse = aliSmsProvider.changeComplaintReport_Admin(telephoneStr.toString(), createUser, customer, level, "", serverName, follow);
                logger.info("短信返回信息为:{}", sendSmsResponse.getMessage());
                logger.info("短信返回码为:{}", sendSmsResponse.getCode());
                String remark = serverName + "转交给" + follow + "后续跟进，请尽快领取并跟进处理！";
                for (User openUser : oppenIdUser) {
                    wechatService.pushWechatMessage(openUser, "TtIURZYEdaD_PHRHpqmoZIrhFwRqA_7-X2CXV5RJIm4", Constants.WECHAT_PUSH_URL, "投诉处理提醒",
                            remark, customer, problemBuffer.substring(0, problemBuffer.length() - 1), complaintReport.getCreationTimeStr(), "", "");
                }
            } else {
                sendSmsResponse = aliSmsProvider.auditComplaintReport(telephoneStr.toString(), createUser, customer, level, complaintReport.getValidTime().toString(), follow);
                logger.info("短信返回信息为:{}", sendSmsResponse.getMessage());
                logger.info("短信返回码为:{}", sendSmsResponse.getCode());
                for (User openUser : oppenIdUser) {
                    wechatService.pushWechatMessage(openUser, "TtIURZYEdaD_PHRHpqmoZIrhFwRqA_7-X2CXV5RJIm4", Constants.WECHAT_PUSH_URL, "投诉处理提醒",
                            "请尽快领取并跟进处理！", customer, problemBuffer.substring(0, problemBuffer.length() - 1), complaintReport.getCreationTimeStr(), "", "");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 封装返回类
     *
     * @param complaintReportList
     * @return
     */
    private List<ComplaintReportAudit> getResponse(List<ComplaintReport> complaintReportList) {
        List<ComplaintReportAudit> auditList = new ArrayList<>();
        for (ComplaintReport complaintReport : complaintReportList) {
            ComplaintReportAudit audit = new ComplaintReportAudit();
            //设置投诉单ID
            audit.setComplaintReportId(complaintReport.getId());
            //设置创建报告人
            ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 193L);
            if (null != complaintReportData && StringUtils.isNotEmpty(complaintReportData.getAnswerOther())) {
                audit.setReportUserName(complaintReportService.getComplaintReportCustomer(complaintReport.getId()));
            }
            //设置备注
            if (StringUtils.isNotEmpty(complaintReport.getOtherFollowNote())) {
                audit.setNote(complaintReport.getOtherFollowNote());
            }
            //设置跟进报告人
            if (null != complaintReport.getFollowUser()) {
                UserProfile userProfile = userProfileRepository.findByUserId(complaintReport.getFollowUser().getId());
                if (null != userProfile && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    audit.setFollowUserName(userProfile.getRealName());
                }
            }
            //设置创建时间
            audit.setCompleteTimeStr(complaintReport.getCreationTimeStr());
            //设置报告状态
            audit.setStatus(ComplaintReportUtil.getReportStatus(complaintReport.getReportStatus()));
            if (null != complaintReport.getValidTime()) {
                audit.setValidTime(complaintReport.getValidTime().toString());
            }
            //如果最近一次的解决方案是自行跟进，那就设置进去
            if (null != complaintReport.getComplaintSolutionId()) {
                audit.setComplaintSolutionId(complaintReport.getComplaintSolutionId());
            }
            //设置实际时间 剩余时间
            if (null != complaintReport.getAuditTime()) {
                ComplaintTimeResponse timeResponse = complaintTimeService.getComplaintTime(complaintReport);
                audit.setActualTime(timeResponse.getTotalTime());
                audit.setTimeRemaining(timeResponse.getRemainingTime());
                audit.setFollowUserTime(timeResponse.getActualProcessingTime());
            }

            auditList.add(audit);
        }
        return auditList;
    }

    /**
     * 更新投诉单
     *
     * @param complaintReport
     * @param complaintReportDataList
     */
    @Override
    public void updateComplaintReport(ComplaintReport complaintReport, ComplaintReportAnswer complaintReportDataList) {
        List<ComplaintReportData> dataList = complaintReportDataRepository.selectAnswer(complaintReport.getId());
        String stationName = "";
        for (ComplaintReportData data : complaintReportDataList.getComplaintReportDataList()) {
            for (ComplaintReportData reportData : dataList) {
                if (data.getQuestionId().equals(reportData.getQuestionId())) {
                    reportData.setAnswerId(data.getAnswerId());
                    reportData.setAnswerOther(data.getAnswerOther());
                    if (data.getQuestionId().equals(192L) && StringUtils.isNotEmpty(data.getAnswerOther())) {
                        Station station = stationRepository.findByStationNum(data.getAnswerOther());
                        if (null != station && StringUtils.isNotEmpty(station.getName())) {
                            stationName = station.getName();
                        }
                    }
                    complaintReportDataRepository.save(reportData);
                }
                ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), data.getQuestionId());
                if (null == complaintReportData) {
                    reportData = new ComplaintReportData();
                    reportData.setAnswerOther(data.getAnswerOther());
                    reportData.setAnswerId(data.getAnswerId());
                    reportData.setComplaintReport(complaintReport);
                    complaintReportDataRepository.save(reportData);
                }
            }
        }
        if (StringUtils.isNotEmpty(stationName)) {
            ComplaintReportData complaintReportData = complaintReportDataRepository.selectByQuestion(complaintReport.getId(), 193L);
            if (null != complaintReportData) {
                complaintReportData.setAnswerOther(stationName);
                complaintReportDataRepository.save(complaintReportData);
            }
        }
    }


}
